package com.mz.mattress.api.util;

import com.mz.mattress.api.entity.SysFile;
import com.mz.mattress.api.enums.FilePrefixEnum;
import com.mz.mattress.api.enums.ObsEnum;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ThreadLocalRandom;

@Slf4j
public class ObsUtil {

    private static ObsConfiguration config;

    private static final String END_POINT = "obs.cn-east-3.myhuaweicloud.com";
    private static final String AK = "MYOF6IZFFJWHXYNHX6OX";
    private static final String SK = "wx8Xefve4RBkgwRzJHuIGCHJ8Mn37O2UkYItHPqV";

    static {
        config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(END_POINT);
    }

    public static String generateSsn() {
        int random = ThreadLocalRandom.current().nextInt(100);
        StringBuilder sb = new StringBuilder();
        sb.append(System.currentTimeMillis());
        if (random < 10) {
            sb.append("0" + random);
        } else {
            sb.append(random);
        }

        return sb.toString();
    }

    public static SysFile upload(MultipartFile file, ObsEnum obsEnum) {
        return upload(file, null, obsEnum);
    }

    public static SysFile upload(MultipartFile file, String fileName, ObsEnum obsEnum) {

        byte[] fileBytes = null;
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            log.error("obs_error", e);
            return null;
        }
        String name = file.getOriginalFilename();
        String ext = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
        return upload(fileBytes, fileName, ext, obsEnum);
    }

    public static SysFile upload(byte[] fileBytes, String fileName, String ext, ObsEnum obsEnum) {
        ObsClient obsClient = null;
        try {
            if (fileName == null) {
                fileName = generateSsn();
            }
            fileName = fileName + "." + ext;
            Integer fileSize = fileBytes.length;
            obsClient = new ObsClient(AK, SK, config);
            PutObjectResult result = obsClient.putObject(obsEnum.bucketName, fileName,
                    new ByteArrayInputStream(fileBytes));
            log.info("obs_url=" + result.getObjectUrl());
            String fileUrl = result.getObjectUrl().replace(obsEnum.rawUrl, obsEnum.mapUrl);
            SysFile sysFile = new SysFile();
            sysFile.setName(fileName);
            sysFile.setSize(Long.parseLong(fileSize.toString()));
            sysFile.setUrl(fileUrl);
            sysFile.setExt(ext);
            return sysFile;
        } catch (Exception e) {
            log.error("obs_upload_error", e);
        } finally {
            com.mz.mattress.api.util.IoUtils.closeQuietly(obsClient);
        }
        return null;
    }

    public static byte[] download(String objectName, ObsEnum obsEnum) {
        // 创建ObsClient实例
        final ObsClient obsClient = new ObsClient(AK, SK, END_POINT);
        ObsObject obsObject = obsClient.getObject(obsEnum.bucketName, objectName);
        InputStream input = obsObject.getObjectContent();
        byte[] bytes = null;
        try {
            bytes = com.mz.mattress.api.util.IoUtils.toBytes(input);
        } catch (IOException e) {
            log.error("obs_download_error", e);
        }
        return bytes;
    }

    public static void delete(String url, ObsEnum obsEnum) {
        // 创建ObsClient实例
        final ObsClient obsClient = new ObsClient(AK, SK, END_POINT);
        String objectName = url.replace(obsEnum.mapUrl + "/", "");
        String bucketName = obsEnum.bucketName;
        obsClient.deleteObject(bucketName, objectName);
        log.info("obs_deleted,bucketName={},objectName={}", bucketName, objectName);
    }

    public static void main(String[] args) {

        final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmss");

        String filePath = "E:\\444.jpg";
        File file = new File(filePath);
        byte[] bytes = com.mz.mattress.api.util.IoUtils.toBytes(file);

        String fileName = FilePrefixEnum.Contract.getPrefix() + FORMATTER.format(LocalDateTime.now()) + (10 + ThreadLocalRandom.current().nextInt(899));
//        SysFile sysFile = ObsUtil.upload(multipartFile, fileName, ObsEnum.HWH_CAR);

        SysFile sysFile = ObsUtil.upload(bytes, fileName, "jpg", ObsEnum.HWH_CAR);
        System.out.println(sysFile.getUrl());

    }
}
